<template>
  <div class="app-container">
    <!-- 全景查看器组件 -->
    <VRViewer ref="viewerRef" @vr-point-changed="handleVRPointChanged" />

    <!-- 控制按钮组 -->
    <div class="controls-container">
      <!-- 控制栏切换按钮 - 独立于右侧控制按钮容器 -->
      <div class="control-toggle-container">
        <button class="control-toggle-btn" :title="controlsHidden ? '显示控制面板' : '隐藏控制面板'"
          @click="toggleControlsVisibility"
          :style="{ background: controlsHidden ? 'rgba(245, 158, 11, 0.7)' : 'rgba(16, 185, 129, 0.7)' }">
          <i class="fas fa-sliders-h"></i>
        </button>
      </div>

      <!-- 右侧控制按钮容器 - 使用Flexbox实现动态排列 -->
      <div class="right-controls-container" :class="{ 'hidden-control': controlsHidden }">
        <div v-for="button in controlButtons" :key="button.id"
          :class="button.containerClass">
          <button :class="button.buttonClass" :title="button.title" @click="button.handler">
            <i v-if="button.icon" :class="['fas', button.getIcon ? button.getIcon() : button.icon]"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 右下角独立的音频控制按钮 -->
    <div class="audio-player-float" :class="{ 'hidden-control': controlsHidden }">
      <button class="audio-player-btn" :class="{ 'audio-player-btn-playing': isAudioPlaying }" :style="audioButtonStyle"
        :title="'控制语音讲解和背景音乐'" @click="toggleAudio">
        <i class="fas fa-music"></i>
      </button>
    </div>

    <!-- 功能面板组件 -->
    <CommentBoard ref="commentBoardRef" :point-id="currentVrPointId" :controls-hidden="controlsHidden" />

    <Gallery ref="galleryRef" />

    <InfluencerTrail ref="influencerTrailRef" :point-id="currentVrPointId" :controls-hidden="controlsHidden" />

    <!-- 图片预览模态框 -->
    <div ref="imagePreviewRef" class="image-preview-overlay" @click="closeImagePreview">
      <div class="image-preview-container">
        <img ref="previewImageRef" class="preview-image" :src="previewImageSrc" alt="预览图片" @click.stop />
        <button class="close-preview" @click="closeImagePreview" title="关闭">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>

  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import VRViewer from './components/VRViewer.vue'
import CommentBoard from './components/CommentBoard.vue'
import Gallery from './components/Gallery.vue'
import InfluencerTrail from './components/InfluencerTrail.vue'
import audioService, { audioPlaying, bgmPlaying } from './services/audioService.js'

export default {
  name: 'App',
  components: {
    VRViewer,
    CommentBoard,
    Gallery,
    InfluencerTrail
  },
  setup() {
    // 组件引用
    const viewerRef = ref(null)
    const commentBoardRef = ref(null)
    const galleryRef = ref(null)
    const influencerTrailRef = ref(null)
    const imagePreviewRef = ref(null)
    const previewImageRef = ref(null)

    // 图片预览状态
    const previewImageSrc = ref('')

    // 状态管理
    const controlsHidden = ref(false)
    const currentVrPointId = ref(null)
    const currentVrItem = ref(null)
    const currentRotation = ref(0) // 保存音频按钮当前的旋转角度

    // 计算属性，用于在暂停时保持按钮的旋转角度
    const audioButtonStyle = computed(() => {
      if (!isAudioPlaying.value) {
        return {
          transform: `rotate(${currentRotation.value}deg)`
        }
      }
      return {}
    })

    // 延迟播放音频，确保组件完全加载和渲染完成
    const deferredAudioPlayback = (item) => {
      if (!item) return

      // 使用requestAnimationFrame确保在浏览器渲染周期的空闲时间执行
      requestAnimationFrame(() => {
        // 添加额外的setTimeout确保组件完全加载
        setTimeout(() => {
          // 创建Promise数组用于并行处理音频播放
          const audioPromises = []

          // 播放讲解音频
          if (item.mp3Url) {
            audioPromises.push(
              audioService.playVrAudio(item)
                .then(result => result)
                .catch(error => {
                  console.error('讲解音频播放失败:', error)
                  return null
                })
            )
          }

          // 播放背景音乐
          if (item.bgm) {
            audioPromises.push(
              audioService.playBgm(item)
                .then(result => result)
                .catch(error => {
                  console.error('背景音乐播放失败:', error)
                  return null
                })
            )
          }

          // 处理所有音频播放的结果
          Promise.all(audioPromises).then(results => {
            // 检查是否有需要用户交互的结果
            const interactionRequired = results.find(result => result && result.requiresUserInteraction)
            if (interactionRequired) {
              showAudioPlayPrompt(interactionRequired.item, interactionRequired.isBgm)
            }
          })
        }, 500)
      })
    }

    // 处理VR点变化事件
    const handleVRPointChanged = (pointData) => {
      currentVrPointId.value = pointData.pointId
      currentVrItem.value = pointData.item

      // 当VR点变化时，尝试播放新的音频和背景音乐
      if (currentVrItem.value) {
        // 延迟播放音频，确保组件完全加载和渲染完成
        deferredAudioPlayback(currentVrItem.value)
      } else {
        // 如果没有音频，停止当前播放的所有音频
        audioService.stopAllAudio()
      }
    }

    // 切换控制面板可见性
    const toggleControlsVisibility = () => {
      controlsHidden.value = !controlsHidden.value

      // 当显示控制面板时，确保留言板也显示
      if (!controlsHidden.value && commentBoardRef.value) {
        commentBoardRef.value.toggleCommentBoard()
      }
    }

    // 切换留言板显示
    const toggleCommentBoard = () => {
      if (commentBoardRef.value) {
        commentBoardRef.value.toggleCommentBoard()
      }
    }

    // 显示上一个VR
    const showPreviousVR = () => {
      if (viewerRef.value) {
        viewerRef.value.showPreviousVR()
      }
    }

    // 显示下一个VR
    const showNextVR = () => {
      if (viewerRef.value) {
        viewerRef.value.showNextVR()
      }
    }

    // 切换画廊显示
    const toggleGallery = () => {
      if (galleryRef.value) {
        galleryRef.value.toggleGallery()
      }
    }

    // 切换达人足迹显示
    const toggleInfluencerTrail = () => {
      if (influencerTrailRef.value) {
        influencerTrailRef.value.toggleInfluencerTrail()
      }
    }

    // 显示图片预览
    const showImagePreview = (imageSrc) => {
      if (!imageSrc || typeof imageSrc !== 'string') {
        return
      }

      previewImageSrc.value = imageSrc

      if (imagePreviewRef.value) {
        // 移除旧的active类然后添加，以重新触发动画
        imagePreviewRef.value.classList.remove('active')
        void imagePreviewRef.value.offsetWidth // 触发重排
        imagePreviewRef.value.classList.add('active')

        // 阻止页面滚动
        document.body.style.overflow = 'hidden'
      }
    }

    // 关闭图片预览
    const closeImagePreview = () => {
      if (imagePreviewRef.value) {
        imagePreviewRef.value.classList.remove('active')

        // 恢复页面滚动
        document.body.style.overflow = ''
      }
    }

    // 切换所有音频播放状态
    const toggleAudio = () => {
      if (audioPlaying.value || bgmPlaying.value) {
        // 在停止音频前，捕获当前的旋转角度
        const audioButton = document.querySelector('.audio-player-btn')
        if (audioButton) {
          // 获取当前的变换矩阵
          const style = window.getComputedStyle(audioButton)
          const matrix = new DOMMatrix(style.transform)

          // 计算旋转角度（弧度转角度）
          const angle = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI)

          // 标准化角度为0-359
          currentRotation.value = ((angle % 360) + 360) % 360
        }
      }

      audioService.toggleAllPlayback(currentVrItem.value)
        .then(result => {
          // 如果需要用户交互，显示音频播放提示
          if (result && result.requiresUserInteraction) {
            showAudioPlayPrompt(result.item)
          }
        })
        .catch(error => {
          console.error('音频控制失败:', error)
        })
    }

    // 计算属性，用于确保组件能正确响应外部导入的响应式状态变化
    const isAudioPlaying = computed(() => audioPlaying.value || bgmPlaying.value)

    // 显示音频播放提示
    const showAudioPlayPrompt = (item) => {
      if (!item || (!item.mp3Url && !item.bgm)) {
        return
      }

      // 检查是否已经存在提示框，如果有则移除
      const existingPrompt = document.querySelector('.audio-play-prompt')
      if (existingPrompt) {
        existingPrompt.remove()
      }

      // 创建音频播放提示框
      const promptHTML = `
        <div class="audio-play-prompt">
          <div class="audio-prompt-content">
            <div class="audio-prompt-icon">
              <i class="fas fa-headphones-alt fa-2x"></i>
            </div>
            <div class="audio-prompt-text">
              <p>点击播放语音讲解和背景音乐</p>
            </div>
            <button id="audio-prompt-play-btn" class="audio-prompt-play-btn">
              <i class="fas fa-play"></i>
            </button>
            <button id="audio-prompt-close-btn" class="audio-prompt-close-btn">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
      `

      document.body.insertAdjacentHTML('beforeend', promptHTML)

      const audioPrompt = document.querySelector('.audio-play-prompt')
      const playBtn = document.getElementById('audio-prompt-play-btn')
      const closeBtn = document.getElementById('audio-prompt-close-btn')

      // 添加播放按钮事件
      if (playBtn) {
        playBtn.addEventListener('click', () => {
          // 同时播放讲解音频和背景音乐
          const promises = []

          if (item.mp3Url) {
            promises.push(
              audioService.playVrAudio(item)
                .then(() => true)
                .catch(error => {
                  console.error('讲解音频播放失败: ', error)
                  return false
                })
            )
          }

          if (item.bgm) {
            promises.push(
              audioService.playBgm(item)
                .then(() => true)
                .catch(error => {
                  console.error('背景音乐播放失败: ', error)
                  return false
                })
            )
          }

          Promise.all(promises).then(results => {
            const allFailed = results.every(success => !success)
            if (allFailed) {
              alert('音频播放失败，请稍后再试')
            } else {
              // 移除提示框
              if (audioPrompt) {
                audioPrompt.remove()
              }
            }
          })
        })
      }

      // 添加关闭按钮事件
      if (closeBtn) {
        closeBtn.addEventListener('click', () => {
          if (audioPrompt) {
            audioPrompt.remove()
          }
        })
      }

      // 添加点击外部关闭提示框的功能
      if (audioPrompt) {
        audioPrompt.addEventListener('click', (e) => {
          if (e.target === audioPrompt) {
            audioPrompt.remove()
          }
        })

        // 30秒后自动关闭提示框
        setTimeout(() => {
          if (audioPrompt && document.contains(audioPrompt)) {
            audioPrompt.remove()
          }
        }, 30000)
      }
    }

    // 生命周期钩子
    onMounted(() => {
      // 组件初始化完成

      // 绑定图片点击事件
      const handleImageClick = (e) => {
        // 只处理普通图片，不处理预览模态框中的图片、VR相关的特殊图片和画廊项中的图片
        if (e.target.tagName === 'IMG' &&
          !e.target.closest('.image-preview-container') &&
          !e.target.closest('#viewer') &&
          !e.target.closest('.gallery-item')) {

          const imgSrc = e.target.getAttribute('src')
          if (imgSrc) {
            // 阻止默认行为
            e.preventDefault()
            e.stopPropagation()

            // 显示图片预览
            showImagePreview(imgSrc)
          }
        }
      }

      // 监听document上的点击事件，委托给所有图片
      document.addEventListener('click', handleImageClick, true)

      // 监听画廊项点击事件，跳转到对应的VR视图
      const handleGalleryItemClick = (e) => {
        if (e.detail && e.detail.item && viewerRef.value) {
          const item = e.detail.item
          viewerRef.value.showVRById(item.pointVrId || item.id)
        }
      }
      window.addEventListener('gallery-item-click', handleGalleryItemClick)
      window._galleryItemClickHandler = handleGalleryItemClick

      // 监听键盘事件，ESC键关闭预览
      const handleKeyDown = (e) => {
        if (e.key === 'Escape') {
          closeImagePreview()
        }
      }

      document.addEventListener('keydown', handleKeyDown)

      // 保存事件处理器以便在组件卸载时移除
      window._imageClickHandler = handleImageClick
      window._keyDownHandler = handleKeyDown
    })

    onUnmounted(() => {
      // 组件清理
      // 移除事件监听器，防止内存泄漏
      if (window._imageClickHandler) {
        document.removeEventListener('click', window._imageClickHandler, true)
        delete window._imageClickHandler
      }

      if (window._galleryItemClickHandler) {
        window.removeEventListener('gallery-item-click', window._galleryItemClickHandler)
        delete window._galleryItemClickHandler
      }

      if (window._keyDownHandler) {
        document.removeEventListener('keydown', window._keyDownHandler)
        delete window._keyDownHandler
      }
    })

    // 控制按钮配置数组 - 统一管理所有右侧功能按钮
    const controlButtons = ref([
      {
        id: 'commentBoard',
        title: '留言板',
        icon: 'fa-comments',
        handler: toggleCommentBoard,
        containerClass: 'comment-board-container',
        buttonClass: 'comment-board-btn'
      },
      {
        id: 'influencerTrail',
        title: '达人足迹',
        icon: 'fa-user-tie',
        handler: toggleInfluencerTrail,
        containerClass: 'influencer-trail-container',
        buttonClass: 'influencer-trail-btn'
      },
      {
        id: 'gallery',
        title: '图片列表',
        icon: 'fa-images',
        handler: toggleGallery,
        containerClass: 'gallery-container',
        buttonClass: 'gallery-btn'
      },
      {
        id: 'prevVR',
        title: '上一个VR',
        icon: 'fa-chevron-up',
        handler: showPreviousVR,
        containerClass: 'vr-prev-container',
        buttonClass: 'vr-prev-btn'
      },
      {
        id: 'nextVR',
        title: '下一个VR',
        icon: 'fa-chevron-down',
        handler: showNextVR,
        containerClass: 'vr-next-container',
        buttonClass: 'vr-next-btn'
      }
    ])

    return {
      viewerRef,
      commentBoardRef,
      galleryRef,
      influencerTrailRef,
      imagePreviewRef,
      previewImageRef,

      controlsHidden,
      currentVrPointId,
      currentVrItem,
      audioPlaying,
      bgmPlaying,
      previewImageSrc,
      controlButtons,
      isAudioPlaying,
      currentRotation,
      audioButtonStyle,
      handleVRPointChanged,
      toggleControlsVisibility,
      showPreviousVR,
      showNextVR,
      toggleGallery,
      toggleInfluencerTrail,
      toggleAudio,
      toggleCommentBoard,
      showImagePreview,
      closeImagePreview
    }
  }
}
</script>

<style scoped>
.app-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

/* 右下角音频控制按钮样式 */
.audio-player-float {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 150;
}

.audio-player-btn {
  width: 60px;
  height: 60px;
  border: none;
  border-radius: 50%;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  font-size: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  opacity: 0.9;
  position: relative;
  overflow: hidden;
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

/* 音频播放时的旋转动画效果 */
.audio-player-btn-playing {
  background: rgba(239, 68, 68, 1);
  animation: audio-rotate 2s linear infinite;
  box-shadow: 0 6px 20px rgba(239, 68, 68, 0.4);
}

@keyframes audio-rotate {
  0% {
    transform: rotate(0deg);
    box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3);
  }

  50% {
    box-shadow: 0 6px 24px rgba(239, 68, 68, 0.5);
  }

  100% {
    transform: rotate(360deg);
    box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3);
  }
}

@keyframes audio-rotate-reverse {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(-360deg);
  }
}

.audio-player-btn:hover {
  transform: scale(1.1);
  opacity: 1;
}

.audio-player-btn:active {
  transform: scale(0.95);
}

/* 控制按钮容器样式 - Web端默认样式 - 永远位于控制切换按钮下方 */
.right-controls-container {
  position: fixed;
  top: 140px; /* 控制切换按钮下方（80px + 50px按钮高度 + 10px间距） */
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 140;
}

/* Web端除了控制栏切换按钮外，所有按钮容器使用静态定位，避免与Flexbox布局冲突 */
.comment-board-container,
.gallery-container,
.influencer-trail-container,
.vr-prev-container,
.vr-next-container,
.audio-control-container,
.audio-controls-container {
  position: static !important;
  right: auto !important;
  top: auto !important;
  margin: 0;
}

/* 控制栏切换按钮独立固定定位 - 始终在右上方 */
.control-toggle-container {
  position: fixed !important;
  top: 80px !important;
  right: 20px !important;
  z-index: 150 !important;
}

/* 按钮的定位已由.right-controls-container统一管理 */

/* 统一按钮样式 */
.control-toggle-btn,
.comment-board-btn,
.gallery-btn,
.influencer-trail-btn,
.vr-prev-btn,
.vr-next-btn,
.audio-control-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50%;
  color: white;
  cursor: pointer;
  font-size: 22px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  opacity: 0.8;
  overflow: hidden;
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

/* 各按钮颜色 */
.control-toggle-btn {
  background: rgba(16, 185, 129, 0.7);
  /* 默认半透明绿色 */
}

.comment-board-btn {
  background: rgba(14, 165, 233, 0.7);
  /* 半透明蓝色，与其他按钮区分 */
}

.gallery-btn {
  background: rgba(139, 92, 246, 0.7);
  /* 半透明紫色 */
}

.influencer-trail-btn {
  background: rgba(247, 127, 0, 0.7);
  /* 半透明橙色 */
}

.vr-prev-btn,
.vr-next-btn {
  background: rgba(37, 99, 235, 0.7);
  /* 半透明蓝色 */
}

.audio-control-btn {
  background: rgba(239, 68, 68, 0.7);
  /* 半透明红色，与其他按钮区分 */
}

/* 统一按钮悬停效果 */
.control-toggle-btn:hover,
.comment-board-btn:hover,
.gallery-btn:hover,
.influencer-trail-btn:hover,
.vr-prev-btn:hover,
.vr-next-btn:hover,
.audio-control-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
  opacity: 1;
}

/* 统一按钮点击效果 */
.control-toggle-btn:active,
.comment-board-btn:active,
.gallery-btn:active,
.influencer-trail-btn:active,
.vr-prev-btn:active,
.vr-next-btn:active,
.audio-control-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 统一按钮图标旋转效果 */
.control-toggle-btn i,
.comment-board-btn i,
.gallery-btn i,
.influencer-trail-btn i,
.vr-prev-btn i,
.vr-next-btn i,
.audio-control-btn i {
  margin: 0;
  transition: transform 0.3s ease;
}

.control-toggle-btn:hover i,
.comment-board-btn:hover i,
.gallery-btn:hover i,
.influencer-trail-btn:hover i,
.audio-control-btn:hover i {
  transform: rotate(15deg);
}

.vr-prev-btn:hover i {
  transform: translateY(-2px);
}

.vr-next-btn:hover i {
  transform: translateY(2px);
}

/* 隐藏状态类 */
.hidden-control {
  display: none !important;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  /* 移动端音频控制按钮适配 */
  .audio-player-float {
    right: 15px;
    bottom: 15px;
  }

  .audio-player-btn {
    width: 55px;
    height: 55px;
    font-size: 22px;
  }

  /* 移动端右侧控制按钮容器调整 - 永远位于控制切换按钮下方 */
  .right-controls-container {
    top: 80px; /* 控制切换按钮下方（20px + 50px按钮高度 + 10px间距） */
    right: 15px;
  }

  /* 移除各个按钮容器的固定top值 */
  .comment-board-container,
  .influencer-trail-container,
  .gallery-container,
  .vr-prev-container,
  .vr-next-container {
    position: static !important;
  }

  /* 统一移动端按钮尺寸 */
  .control-toggle-btn,
  .comment-board-btn,
  .gallery-btn,
  .influencer-trail-btn,
  .audio-control-btn,
  .vr-prev-btn,
  .vr-next-btn {
    width: 50px !important;
    height: 50px !important;
    font-size: 20px !important;
    margin: 5px 0 !important;
  }

  /* 移动端控制栏切换按钮定位 - 始终在右上方 */
  .control-toggle-container {
    right: 15px !important;
    top: 20px !important;
  }
}

/* 安全区域适配 - 针对有刘海屏的设备 */
@supports (padding: max(0px)) {

  /* 右侧控制按钮容器 - 安全区域适配 - 永远位于控制切换按钮下方 */
  .right-controls-container {
    right: max(15px, env(safe-area-inset-right));
    top: max(80px, env(safe-area-inset-top) + 60px); /* 控制切换按钮下方 */
  }

  /* 移除各个按钮容器的固定位置值 */
  .comment-board-container,
  .gallery-container,
  .influencer-trail-container,
  .vr-prev-container,
  .vr-next-container {
    right: auto !important;
    top: auto !important;
  }

  /* 音频控制按钮安全区域适配 */
  .audio-player-float {
    right: max(15px, env(safe-area-inset-right));
    bottom: max(15px, env(safe-area-inset-bottom));
  }

  /* 控制栏切换按钮安全区域适配 - 始终在右上方 */
  .control-toggle-container {
    right: max(15px, env(safe-area-inset-right)) !important;
    top: max(15px, env(safe-area-inset-top)) !important;
  }
}

/* 确保在横屏模式下的适配 */
@media (max-width: 768px) and (orientation: landscape) {

  /* 横屏模式下右侧控制按钮容器 - 水平排列，控制切换按钮仍在上方 */
  .right-controls-container {
    top: 80px;
    right: 15px;
    flex-direction: row;
    gap: 15px;
  }

  /* 移除横屏模式下各个按钮容器的固定位置值 */
  .comment-board-container,
  .gallery-container,
  .influencer-trail-container,
  .vr-prev-container,
  .vr-next-container {
    top: auto !important;
    right: auto !important;
  }

  /* 横屏模式下控制栏切换按钮 - 保持在右上方 */
  .control-toggle-container {
    right: 15px !important;
    top: 15px !important;
  }

  /* 横屏模式下音频控制按钮适配 */
  .audio-player-float {
    right: max(15px, env(safe-area-inset-right));
    bottom: max(15px, env(safe-area-inset-bottom));
  }

  .audio-player-btn {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
}
</style>